package com.ruoyi.buy.service.impl;

import com.ruoyi.buy.domain.entity.PO.*;
import com.ruoyi.buy.domain.entity.buy0003.Buy0003AddPostAndItem;
import com.ruoyi.buy.domain.entity.buy0003.Buy0003GetInfoByIdVO;
import com.ruoyi.buy.domain.entity.buy0003.Buy0003GetNotPostItem;
import com.ruoyi.buy.domain.entity.importPO.BuyBatchPurchaseBillImport;
import com.ruoyi.buy.mapper.PO.*;
import com.ruoyi.buy.service.IBuyPurchaseBillService;
import com.ruoyi.buy.service.ICommonService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-12-05
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BuyPurchaseBillServiceImpl implements IBuyPurchaseBillService
{
    @Resource
    private BuyPurchaseBillMapper buyPurchaseBillMapper;

    @Resource
    private BuyPurchaseBillItemMapper buyPurchaseBillItemMapper;

    @Resource
    private BuyPurchaseInvoiceMapper buyPurchaseInvoiceMapper;

    @Resource
    private ICommonService commonService;

    @Resource BuyPurchasePostItemMapper buyPurchasePostItemMapper;

    @Resource
    BuyPurchasePostMapper buyPurchasePostMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public Buy0003GetInfoByIdVO selectBuyPurchaseBillById(Long id)
    {
        BuyPurchaseBill buyPurchaseBill = buyPurchaseBillMapper.selectBuyPurchaseBillById(id);
        BuyPurchaseBillItem buyPurchaseBillItem = new BuyPurchaseBillItem();
        buyPurchaseBillItem.setnMainId(id);
        List<BuyPurchaseBillItem> itemList = this.buyPurchaseBillItemMapper.selectBuyPurchaseBillItemList(buyPurchaseBillItem);
        Buy0003GetInfoByIdVO result = new Buy0003GetInfoByIdVO();
        result.setBillPO(buyPurchaseBill);
        result.setItemPOList(itemList);
        return result;
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param buyPurchaseBill 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<BuyPurchaseBill> selectBuyPurchaseBillList(BuyPurchaseBill buyPurchaseBill)
    {
        return buyPurchaseBillMapper.selectBuyPurchaseBillList(buyPurchaseBill);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param para 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertBuyPurchaseBill(Buy0003GetInfoByIdVO para) throws Exception {
        BuyPurchaseBill buyPurchaseBill = para.getBillPO();
        buyPurchaseBill.setCreateTime(DateUtils.getNowDate());
        buyPurchaseBill.setCreateBy(para.getCreateBy());
        buyPurchaseBillMapper.insertBuyPurchaseBill(buyPurchaseBill);

        //反查主表Id
        List<BuyPurchaseBill>bills = this.selectBuyPurchaseBillList(buyPurchaseBill);
        if (!bills.isEmpty() && bills.get(0).getId() != null){
            Long nMainId = bills.get(0).getId();
            List<BuyPurchaseBillItem> itemList = para.getItemPOList();
            for (BuyPurchaseBillItem item:itemList
                 ) {
                item.setnMainId(nMainId);
                item.setCreateTime(DateUtils.getNowDate());
                item.setCreateBy(para.getCreateBy());
                buyPurchaseBillItemMapper.insertBuyPurchaseBillItem(item);

                this.commonService.changeSpaPrice(buyPurchaseBill,item,para.getCreateBy(),buyPurchaseBill.getvBillNo(),"BUY0003",buyPurchaseBill.getvType());
            }
        }
        return 1;
    }



    /**
     * 修改【请填写功能名称】
     * 
     * @param buyPurchaseBill 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateBuyPurchaseBill(BuyPurchaseBill buyPurchaseBill)
    {
        buyPurchaseBill.setUpdateTime(DateUtils.getNowDate());
//        buyPurchaseBill.setStatus("1");
        return buyPurchaseBillMapper.updateBuyPurchaseBill(buyPurchaseBill);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteBuyPurchaseBillByIds(Long[] ids)
    {
        return buyPurchaseBillMapper.deleteBuyPurchaseBillByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteBuyPurchaseBillById(Long id)
    {
        return buyPurchaseBillMapper.deleteBuyPurchaseBillById(id);
    }

    /**
     * 查询采购发票列表
     *
     * @param buyPurchaseInvoice 采购发票
     * @return 采购发票
     */
    @Override
    public List<BuyPurchaseInvoice> selectBuyPurchaseInvoiceList(BuyPurchaseInvoice buyPurchaseInvoice)
    {
        return buyPurchaseInvoiceMapper.selectBuyPurchaseInvoiceList(buyPurchaseInvoice);
    }

    /**
     * 修改采购发票
     *
     * @param buyPurchaseInvoice 采购发票
     * @return 结果
     */
    @Override
    public int updateBuyPurchaseInvoice(BuyPurchaseInvoice buyPurchaseInvoice)
    {
        buyPurchaseInvoice.setUpdateTime(DateUtils.getNowDate());
        return buyPurchaseInvoiceMapper.updateBuyPurchaseInvoice(buyPurchaseInvoice);
    }

    @Override
    public int saveInvoice(Buy0003GetInfoByIdVO para) {
        //主表信息
        BuyPurchaseBill buyPurchaseBill = para.getBillPO();

        //发票信息
        List<BuyPurchaseInvoice> invoiceList = para.getInvoiceList();

        //遍历发票信息，有Id的判断是否有修改，然后做update，没有id的直接新增
        for (BuyPurchaseInvoice invoice:invoiceList
             ) {
            if (invoice.getId() == null || invoice.getId() == 0){
                invoice.setStatus("0");
                invoice.setDelFlag("0");
                invoice.setnMainId(buyPurchaseBill.getId());
                invoice.setCreateBy(para.getCreateBy());
                invoice.setCreateTime(DateUtils.getNowDate());
                this.buyPurchaseInvoiceMapper.insertBuyPurchaseInvoice(invoice);
            }else{
                BuyPurchaseInvoice condition = new BuyPurchaseInvoice();
                condition.setnMainId(invoice.getnMainId());
                condition.setStatus("0");
                condition.setDelFlag("0");
                List<BuyPurchaseInvoice> resultList = this.buyPurchaseInvoiceMapper.selectBuyPurchaseInvoiceList(condition);
                if (!resultList.isEmpty()){
                    resultList.get(0).setvInvocieNo(invoice.getvInvocieNo());
                    invoice.setUpdateBy(para.getCreateBy());
                    invoice.setUpdateTime(DateUtils.getNowDate());
                    this.buyPurchaseInvoiceMapper.updateBuyPurchaseInvoice(invoice);
                }
            }
        }
        return 1;
    }

    @Override
    public void importBatchSave(List<BuyBatchPurchaseBillImport> para ) throws Exception {
        //去除每条数据的合同号，再去重
        List<String> listBillNo = para.stream().map(BuyBatchPurchaseBillImport::getvBillNo).distinct().collect(Collectors.toList());

        for (String vBillNo:listBillNo
             ) {
            List<BuyBatchPurchaseBillImport> billItemList= para.stream().filter(x -> x.getvBillNo().equals(vBillNo)).collect(Collectors.toList());;
            BuyPurchaseBill buyPurchaseBill = new BuyPurchaseBill();



            BuyBatchPurchaseBillImport billItemOne = billItemList.get(0);
            buyPurchaseBill.setvBillNo(billItemOne.getvBillNo());

            buyPurchaseBill.setStatus("1");
            buyPurchaseBill.setCreateTime(DateUtils.getNowDate());
            buyPurchaseBill.setSupplier(billItemOne.getSupplier());
            buyPurchaseBill.setvBrand(billItemOne.getvSpaBrand());
            buyPurchaseBill.setnDays(billItemOne.getNDays());
            buyPurchaseBill.setRemark(billItemOne.getvSupplierNo());
            buyPurchaseBill.setContractTime(billItemOne.getContractTime());
            buyPurchaseBill.setCreateBy(commonService.getUsername());
            //01机加，02外采
            buyPurchaseBill.setvType("02");
            this.buyPurchaseBillMapper.insertBuyPurchaseBill(buyPurchaseBill);

            buyPurchaseBill = this.selectBuyPurchaseBillList(buyPurchaseBill).get(0);

            Long nMainId = buyPurchaseBill.getId();

            for (BuyBatchPurchaseBillImport item:billItemList
                 ) {
                //新增明细
                BuyPurchaseBillItem buyPurchaseBillItem = new BuyPurchaseBillItem();
                buyPurchaseBillItem.setnMainId(nMainId);
                buyPurchaseBillItem.setStatus("0");
                buyPurchaseBillItem.setCreateTime(DateUtils.getNowDate());
                buyPurchaseBillItem.setvSpaName(item.getVSpaName());
                buyPurchaseBillItem.setvSpaModel(item.getvSpaModel());
                buyPurchaseBillItem.setvSpaBrand(item.getvSpaBrand());
                buyPurchaseBillItem.setnQty(item.getnQty());
                buyPurchaseBillItem.setnPrice(item.getnPrice());
                buyPurchaseBillItem.setnDays(item.getNDays());
                buyPurchaseBillItem.setSupplier(item.getSupplier());
                buyPurchaseBillItem.setRemark(item.getRemark());
                buyPurchaseBillItem.setCreateBy(commonService.getUsername());
                buyPurchaseBillItem.setvProjectNo(item.getvProjectNo());
                buyPurchaseBillItem.setvProjectDec(item.getvProjectDec());
                buyPurchaseBillItem.setApplyBy(item.getApplyBy());
                buyPurchaseBillItem.setvBuyNo(item.getvBuyNo());
                this.buyPurchaseBillItemMapper.insertBuyPurchaseBillItem(buyPurchaseBillItem);

                this.commonService.changeSpaPrice(buyPurchaseBill,buyPurchaseBillItem,buyPurchaseBill.getCreateBy(),buyPurchaseBill.getvBillNo(),"BUY0003",buyPurchaseBill.getvType());

//                //发票
//                if(item.getvInvoiceNo() != null && !item.getvInvoiceNo().equals("")){
//                    BuyPurchaseInvoice buyPurchaseInvoice = new BuyPurchaseInvoice();
//                    buyPurchaseInvoice.setCreateTime(DateUtils.getNowDate());
//                    buyPurchaseInvoice.setnMainId(nMainId);
//                    buyPurchaseInvoice.setStatus("0");
//                    buyPurchaseInvoice.setvInvocieNo(item.getvInvoiceNo());
//                    this.buyPurchaseInvoiceMapper.insertBuyPurchaseInvoice(buyPurchaseInvoice);
//                }
            }
        }
    }

    @Override
    public List<Buy0003GetNotPostItem> getNotPostItem(String vContractNos) {
        List<Buy0003GetNotPostItem> result= new ArrayList<>();
        List<String> vContractNoList = Arrays.asList(vContractNos.split(","));
        for (String item:vContractNoList
             ) {
            List<Buy0003GetNotPostItem> items = this.buyPurchaseBillMapper.getNotPostItem(item);
            result.addAll(items);
        }
        return result;
    }

    @Override
    public List<BuyPurchasePostItem> getPostItem(BuyPurchasePost para) {
        BuyPurchasePostItem buyPurchasePostItem = new BuyPurchasePostItem();
        buyPurchasePostItem.setnMainId(para.getId());
        return this.buyPurchasePostItemMapper.selectBuyPurchasePostItemList(buyPurchasePostItem);
    }

    @Override
    public int savePostItem(List<BuyPurchasePostItem> para) {
        BigDecimal nQty = BigDecimal.ZERO;
        for (BuyPurchasePostItem item:para
             ) {
            if (item.getId() == null || item.getId() == 0 ){
                this.buyPurchasePostItemMapper.insertBuyPurchasePostItem(item);
                nQty = item.getnQty();
            }else {
                BuyPurchasePostItem oldData = this.buyPurchasePostItemMapper.selectBuyPurchasePostItemById(String.valueOf(item.getId()));
                nQty = oldData.getnQty().subtract(item.getnQty());
                this.buyPurchasePostItemMapper.updateBuyPurchasePostItem(item);
            }

            //修改合同明细上的发货数量
            //1.先查邮寄主表，要合同编号信息
            BuyPurchasePost buyPurchasePost = this.buyPurchasePostMapper.selectBuyPurchasePostById(item.getnMainId());
            String vContractNos =  buyPurchasePost.getvContractNos();
            String[] vContractNoList = vContractNos.split(",");

            ArrayList< String> arrayList = new ArrayList<String>(vContractNoList.length);
            Collections.addAll(arrayList, vContractNoList);

            //根据合同号查合同
            for (String vContractNo:arrayList
                 ) {
                BuyPurchaseBill buyPurchaseBill = new BuyPurchaseBill();
                buyPurchaseBill.setvBillNo(vContractNo);
                List<BuyPurchaseBill> buyPurchaseBills = this.buyPurchaseBillMapper.selectBuyPurchaseBillList(buyPurchaseBill);
                buyPurchaseBill = buyPurchaseBills.get(0);

                //再查子表零件明细
                BuyPurchaseBillItem buyPurchaseBillItem = new BuyPurchaseBillItem();
                buyPurchaseBillItem.setnMainId(buyPurchaseBill.getId());
                buyPurchaseBillItem.setvSpaName(item.getvSpaName());
                buyPurchaseBillItem.setvSpaBrand(item.getvSpaBrand());
                buyPurchaseBillItem.setvSpaModel(item.getvSpaModel());
                List<BuyPurchaseBillItem> buyPurchaseBillItemList = this.buyPurchaseBillItemMapper.selectBuyPurchaseBillItemList(buyPurchaseBillItem);
                if (buyPurchaseBillItemList !=null && !buyPurchaseBillItemList.isEmpty()){
                    buyPurchaseBillItem = buyPurchaseBillItemList.get(0);
                    if(null == buyPurchaseBillItem.getnPostQty()){
                        buyPurchaseBillItem.setnPostQty(nQty);
                    }else{
                        buyPurchaseBillItem.setnPostQty(nQty.add(buyPurchaseBillItem.getnPostQty()));
                    }
                    this.buyPurchaseBillItemMapper.updateBuyPurchaseBillItem(buyPurchaseBillItem);
                }
            }

        }
        return 1;
    }

    @Override
    public int saveBuyPurchaseBill(Buy0003GetInfoByIdVO para) throws Exception {
        //因为新建合同在请购单那边做，所以这边只有保存修改
        BuyPurchaseBill buyPurchaseBill = para.getBillPO();
        buyPurchaseBill.setUpdateBy(commonService.getUsername());
        buyPurchaseBill.setUpdateTime(DateUtils.getNowDate());
        this.buyPurchaseBillMapper.updateBuyPurchaseBill(buyPurchaseBill);

        //再处理明细，先都删了，然后再新增进去
        BuyPurchaseBillItem buyPurchaseBillItem = new BuyPurchaseBillItem();
        buyPurchaseBillItem.setnMainId(buyPurchaseBill.getId());
        List<BuyPurchaseBillItem> itemList = this.buyPurchaseBillItemMapper.selectBuyPurchaseBillItemList(buyPurchaseBillItem);
        for (BuyPurchaseBillItem item:itemList
             ) {
            this.buyPurchaseBillItemMapper.deleteBuyPurchaseBillItemById(item.getId());
        }
        //然后再都新增进去
        List<BuyPurchaseBillItem> itemPOList = para.getItemPOList();
        for (BuyPurchaseBillItem item:itemPOList
             ) {
            item.setCreateBy(commonService.getUsername());
            item.setCreateTime(DateUtils.getNowDate());
            this.buyPurchaseBillItemMapper.insertBuyPurchaseBillItem(item);
        }
        return 1;
    }

    @Override
    public int updateBillStatus(BuyPurchaseBill para) throws Exception {
        BuyPurchaseBill buyPurchaseBill = this.buyPurchaseBillMapper.selectBuyPurchaseBillById(para.getId());
        if (!buyPurchaseBill.getStatus().equals("0")){
            throw new Exception("该合同状态为非初始状态，请重新确认");
        }
        buyPurchaseBill.setStatus("1");
        this.buyPurchaseBillMapper.updateBuyPurchaseBill(buyPurchaseBill);
        return 1;
    }


//    private void changeSpaPrice(BuyPurchaseBillItem item, String createBy, String vBillNo) throws Exception {
//        //先判断备件表里有没有
//        BuySpaMainInfoPO buySpaMainInfoPO = new BuySpaMainInfoPO();
//        BeanUtils.copyBeanProp(buySpaMainInfoPO,item);
//        buySpaMainInfoPO.setiD(null);
//        List<BuySpaMainInfoPO> spaList = this.buySpaMainInfoMapper.selectSpaInfoByConditions(buySpaMainInfoPO);
//        if (spaList.size() == 0){
//            this.buySpaMainInfoMapper.insertSpaMain(buySpaMainInfoPO);
//        }
//
//        //先查价格
//        BuySpaPricePO buySpaPricePO = new BuySpaPricePO();
//        BeanUtils.copyBeanProp(buySpaPricePO,item);
//        BuySpaPricePO buySpaPriceExist = buySpaPriceMapper.selectSpaPriceByCondition(buySpaPricePO);
//
//        //如果有旧价格，把旧价格作废
//        if (buySpaPriceExist != null && buySpaPriceExist.getiD() != null && buySpaPriceExist.getiD() != 0){
//            if(buySpaPriceExist.getnPrice().compareTo(item.getnPrice()) != 0){
//                buySpaPriceExist.setStatus("1");
//                buySpaPriceExist.setUpdateBy(createBy);
//                int flag = this.buySpaPriceMapper.updateSpaPriceByID(buySpaPriceExist);
//                if (flag!= 1){
//                    throw new Exception("系统异常，请联系管理员");
//                }
//                //新增新价格
//                buySpaPricePO.setStatus("0");
//                buySpaPricePO.setCreateBy(item.getCreateBy());
//                buySpaPricePO.setvContractNo(vBillNo);
//                flag = this.buySpaPriceMapper.insertSpaPrice(buySpaPricePO);
//                if (flag!= 1){
//                    throw new Exception("系统异常，请联系管理员");
//                }
//            }
//        }else{
//            //新增新价格
//            buySpaPricePO.setStatus("0");
//            buySpaPricePO.setCreateBy(item.getCreateBy());
//            buySpaPricePO.setvContractNo(vBillNo);
//            int flag = this.buySpaPriceMapper.insertSpaPrice(buySpaPricePO);
//            if (flag!= 1){
//                throw new Exception("系统异常，请联系管理员");
//            }
//        }
//    }
}
